﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _4Gewinnt
{
    /// <summary>
    /// A game checks who is the active player and whether one player has won
    /// </summary>
    public class Game
    {
        /// <summary>
        /// The game board (readonly)
        /// </summary>
        public Board Board
        {
            get { return _board; }
        }
        private Board _board;

        /// <summary>
        /// The active player (readonly)
        /// </summary>
        public GameColor ActivePlayer
        {
            get { return _activePlayer; }
        }
        private GameColor _activePlayer;

        /// <summary>
        /// True if active player has won (readonly)
        /// </summary>
        public bool HasWon
        {
            get { return _hasWon; }
        }
        private bool _hasWon;

        /// <summary>
        /// True if game is draw (readonly)
        /// </summary>
        public bool Draw
        {
            get { return _draw; }
        }
        private bool _draw;


        /// <summary>
        /// The position of the winning tokens (if no winning: just random stuff)
        /// </summary>
        public int[,] winningPosition;


        /// <summary>
        /// Starts a new game and sets up a start player
        /// </summary>
        /// <param name="startPlayer">The color of the start player</param>
        /// <param name="ttw">The number of consecutive tokens needed to win</param>
        public Game(GameColor startPlayer, int ttw)
        {
            _board = new Board(ttw);
            _activePlayer = startPlayer;
        }

        /// <summary>
        /// Performs a move of the active player
        /// </summary>
        /// <param name="c">The column to move in</param>
        /// <returns>True if move was successfull</returns>
        public bool makeMove(int c)
        {
            //legal move?
            if (_board.isLegalColumn(c))
            {
                //perform move
                _board.moveTo(_activePlayer, c);

                //check whether active player has won
                _hasWon = _board.hasWon(_activePlayer, out winningPosition);

                //check whether game is draw
                if (!_hasWon)
                    _draw = _board.isBoardFull();

                //switch player
                if (!_hasWon && !_draw)
                    if (_activePlayer == GameColor.Blue)
                        _activePlayer = GameColor.Red;
                    else
                        _activePlayer = GameColor.Blue;

                //move was successfull
                return true;
            }
            else
                return false;

        }
    }
}
